package top.ddandang.blog.controller;


import top.ddandang.blog.bean.GlobalResponse;
import top.ddandang.blog.model.pojo.User;
import top.ddandang.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author D
 * @since 2020-06-23
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/userLogin")
    public GlobalResponse userLogin (@RequestParam(value = "username", required = true) String username,
                                     @RequestParam(value = "password", required = true) String password) {

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        log.info(String.valueOf(subject));
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            User user = userService.getUser(username);
            log.warn(String.valueOf(user));

            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getId());
            map.put("nickname", user.getNickname());
            map.put("username", user.getUsername());
            map.put("position", user.getPosition());
            map.put("avatar", user.getAvatar());
            //生成token 并返回给前端
            map.put("token", userService.createToken(user));
            return GlobalResponse.success().data(map).message("登录成功！");

        }catch (UnknownAccountException e){
            return GlobalResponse.failed().code(4001).message("用户名错误！");
        }catch (IncorrectCredentialsException e){
            return GlobalResponse.failed().code(4002).message("密码错误！");
        }
    }

    @PostMapping("/insertUser")
    public GlobalResponse insertUser(String nickname, String username, String password, String passwordCheck) {
        int flag = userService.insertUser(nickname, username, password, passwordCheck);
        if(flag != 1) {
            return GlobalResponse.failed().code(4003).message("两次密码不一样！");
        }else {
            User user = userService.getUser(username);
            log.error(String.valueOf(user));
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getId());
            map.put("nickname", user.getNickname());
            map.put("username", user.getUsername());
            map.put("position", user.getPosition());
            map.put("avatar", user.getAvatar());
            //生成token 并返回给前端
            map.put("token", userService.createToken(user));
            return GlobalResponse.success().data(map).message("注册成功！");
        }
    }

    @GetMapping("/judgeUser")
    public GlobalResponse judgeUser(String username) {
        User user = userService.getUser(username);
        if(user == null) {
            return GlobalResponse.success().message("账号可以用！");
        } else {
            return GlobalResponse.failed().message("账号已存在！");
        }
    }

    @PostMapping("/upLoadUserAvatar")
    public GlobalResponse upLoadUserAvatar(MultipartFile file, String username) {
        String url = userService.upLoadUserAvatar(file);
        userService.updateUserAvatar(url, username);
        return GlobalResponse.success().data("url", url);
    }

    @PostMapping("/updateNickname")
    public GlobalResponse updateNickname(String nickname, String username) {
        int flag = userService.updateNickname(nickname, username);
        if(flag == 1) {
            return GlobalResponse.success().message("修改昵称成功");
        }else {
            return GlobalResponse.failed().message("修改昵称失败");
        }
    }

    @PostMapping("/changePassword")
    public GlobalResponse changePassword(String oldPassword, String password, String username) {

        Boolean isRight = userService.judgePassword(oldPassword, username);
        if(!isRight) {
            return GlobalResponse.failed().message("原始密码错误！");
        }
        int flag = userService.updatePassword(password, username);
        if(flag == 1) {
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed().code(4001);
        }
    }

    @GetMapping("/logOut")
    public GlobalResponse logOut(Integer userId) {
        userService.logOut(userId);
        return GlobalResponse.success().message("登出成功！");
    }
}

